/*
 * RC522.c
 *
 *  Created on: 2019年9月5日
 *      Author: caesar
 */
#include "mfmain.h"
#include "mfrc522.h"
#include <string.h>
#include "../lib/ls1c_delay.h"
#define MAXRLEN 18

unsigned char CT[2];
unsigned char SN[4];
unsigned char DIS[8];
/////////////////////////////////////////////////////////////////////
//功    能：寻卡
//参数说明: req_code[IN]:寻卡方式
//                0x52 = 寻感应区内所有符合14443A标准的卡
//                0x26 = 寻未进入休眠状态的卡
//          pTagType[OUT]：卡片类型代码
//                0x4400 = Mifare_UltraLight
//                0x0400 = Mifare_One(S50)
//                0x0200 = Mifare_One(S70)
//                0x0800 = Mifare_Pro(X)
//                0x4403 = Mifare_DESFire
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdRequest(unsigned char req_code,unsigned char *pTagType)
{
   char status;
   char statuss;
   unsigned int  unLen;
   unsigned char ucComMF522Buf[MAXRLEN];
//  unsigned char xTest ;
   ClearBitMask(Status2Reg,0x08);	   //寄存器包含接收器和发送器和数据模式检测器的状态标志
   WriteRawRC(BitFramingReg,0x07);	   //不启动数据发送
//  xTest = ReadRawRC(BitFramingReg);
//  if(xTest == 0x07 )
 //   { LED_GREEN  =0 ;}
 // else {LED_GREEN =1 ;while(1){}}
   SetBitMask(TxControlReg,0x03);		//TX1、TX2输出信号将传递经发送数据调制的13.56MHz的能量载波信号。

   ucComMF522Buf[0] = req_code;
//   printf("[%d] req_code\r\n",req_code);
   status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,1,ucComMF522Buf,&unLen);	//通过522发送req_code命令，并接收返回数据，存到ucComMF522Buf中
  // printf("%ducComMF522Buf %dunLenr\n",ucComMF522Buf,unLen);
   //     if(status  == MI_OK )
//   { LED_GREEN  =0 ;}
//   else {LED_GREEN =1 ;}
//   printf("[%d status %dunLen\r\n",status,unLen);
   if ((status == MI_OK) && (unLen == 0x10))
//	   if (status == MI_OK)	//这个为啥是0x10，因为是2个字节共16bit
   {
       *pTagType     = ucComMF522Buf[0];
       *(pTagType+1) = ucComMF522Buf[1];			//获取卡类型
//       printf("[%d] *pTagType \r\n",*pTagType );
   }
   else
   {   status = MI_ERR;   }
//   printf("[%d] status9\r\n",status);
   return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：防冲撞
//参数说明: pSnr[OUT]:卡片序列号，4字节
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdAnticoll(unsigned char *pSnr)			 //防冲撞
{
    char status;
    unsigned char i,snr_check=0;
    unsigned int  unLen;
    unsigned char ucComMF522Buf[MAXRLEN];


    ClearBitMask(Status2Reg,0x08);
    WriteRawRC(BitFramingReg,0x00);
    ClearBitMask(CollReg,0x80);

    ucComMF522Buf[0] = PICC_ANTICOLL1;
    ucComMF522Buf[1] = 0x20;

    status = PcdComMF522(PCD_TRANSCEIVE,ucComMF522Buf,2,ucComMF522Buf,&unLen);
//    printf("[%d] status8\r\n",status);
    if (status == MI_OK)
    {
    	 for (i=0; i<4; i++)
         {
             *(pSnr+i)  = ucComMF522Buf[i];
             snr_check ^= ucComMF522Buf[i];
         }
         if (snr_check != ucComMF522Buf[i])
         {   status = MI_ERR;    }
    }

    SetBitMask(CollReg,0x80);
    return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：复位RC522
//返    回: 成功返回MI_OK
/////////////////////////////////////////////////////////////////////
char PcdReset(void)
{
    MF522_RST_PIN_high();
    delay_ms(10);
    MF522_RST_PIN_low();
    delay_ms(10);
    MF522_RST_PIN_high();
    delay_ms(100);
    WriteRawRC(CommandReg,PCD_RESETPHASE);
    delay_us(1);

    WriteRawRC(ModeReg,0x3D);            //和Mifare卡通讯，CRC初始值0x6363
//    printf("[%d] ModeReg\r\n",ReadRawRC(ModeReg));
    WriteRawRC(TReloadRegL,30);
//    printf("[%d] TReloadRegL\r\n",ReadRawRC(TReloadRegL));
    WriteRawRC(TReloadRegH,0);
    WriteRawRC(TModeReg,0x8D);
    WriteRawRC(TPrescalerReg,0x3E);
    WriteRawRC(TxAutoReg,0x40);
    return MI_OK;
}
//////////////////////////////////////////////////////////////////////

//设置RC632的工作方式

//////////////////////////////////////////////////////////////////////
char M500PcdConfigISOType(unsigned char type)
{
   if (type == 'A')                     //ISO14443_A
   {
       ClearBitMask(Status2Reg,0x08);

 /*     WriteRawRC(CommandReg,0x20);    //as default
       WriteRawRC(ComIEnReg,0x80);     //as default
       WriteRawRC(DivlEnReg,0x0);      //as default
	   WriteRawRC(ComIrqReg,0x04);     //as default
	   WriteRawRC(DivIrqReg,0x0);      //as default
	   WriteRawRC(Status2Reg,0x0);//80    //trun off temperature sensor
	   WriteRawRC(WaterLevelReg,0x08); //as default
       WriteRawRC(ControlReg,0x20);    //as default
	   WriteRawRC(CollReg,0x80);    //as default
*/
       WriteRawRC(ModeReg,0x3D);//3F
/*	   WriteRawRC(TxModeReg,0x0);      //as default???
	   WriteRawRC(RxModeReg,0x0);      //as default???
	   WriteRawRC(TxControlReg,0x80);  //as default???
	   WriteRawRC(TxSelReg,0x10);      //as default???
   */
       WriteRawRC(RxSelReg,0x86);//84
 //      WriteRawRC(RxThresholdReg,0x84);//as default
 //      WriteRawRC(DemodReg,0x4D);      //as default
 //      WriteRawRC(ModWidthReg,0x13);//26
       WriteRawRC(RFCfgReg,0x7F);   //4F
  /*   WriteRawRC(GsNReg,0x88);        //as default???
	   WriteRawRC(CWGsCfgReg,0x20);    //as default???
       WriteRawRC(ModGsCfgReg,0x20);   //as default???
*/
   	   WriteRawRC(TReloadRegL,30);//tmoLength);// TReloadVal = 'h6a =tmoLength(dec)
	   WriteRawRC(TReloadRegH,0);
       WriteRawRC(TModeReg,0x8D);
	   WriteRawRC(TPrescalerReg,0x3E);


  //     PcdSetTmo(106);
	   delay_ms(10);
       PcdAntennaOn();
   }
   else{ return (char)-1; }

   return MI_OK;
}
/////////////////////////////////////////////////////////////////////
//功    能：读RC632寄存器
//参数说明：Address[IN]:寄存器地址
//返    回：读出的值
/////////////////////////////////////////////////////////////////////
unsigned char ReadRawRC(unsigned char Address)
{
     unsigned char i, ucAddr;
     unsigned char ucResult=0;

     //MF522_SCK_PIN_low();
     MF522_NSS_PIN_low();
     ucAddr = ((Address<<1)&0x7E)|0x80;

     for(i=8;i>0;i--)
     {
    	 MF522_SCK_PIN_low();
    	 if(ucAddr&0x80)
    		 MF522_SI_PIN_high();
    	 else
    		 MF522_SI_PIN_low();
         MF522_SCK_PIN_high();
         ucAddr <<= 1;
//         MF522_SCK_PIN_low();
     }

     for(i=8;i>0;i--)
     {
         MF522_SCK_PIN_low();
         ucResult <<= 1;
         MF522_SCK_PIN_high();
         gpio_init(MF522_SO_PIN, gpio_mode_input);
//         ucResult|=gpio_get(MF522_SO_PIN);
        if(gpio_get(MF522_SO_PIN)==1)
        	ucResult|=1;
     }

     MF522_NSS_PIN_high();
     MF522_SCK_PIN_high();
     return ucResult;
}

/////////////////////////////////////////////////////////////////////
//功    能：写RC632寄存器
//参数说明：Address[IN]:寄存器地址
//          value[IN]:写入的值
/////////////////////////////////////////////////////////////////////
void WriteRawRC(unsigned char Address, unsigned char value)
{
    unsigned char i, ucAddr;

    MF522_SCK_PIN_low();
    MF522_NSS_PIN_low();
    ucAddr = ((Address<<1)&0x7E);

    for(i=8;i>0;i--)
    {
    	if(ucAddr&0x80)
    	    MF522_SI_PIN_high();
    	else
    	    MF522_SI_PIN_low();
        MF522_SCK_PIN_high();
        ucAddr <<= 1;
        MF522_SCK_PIN_low();
    }

    for(i=8;i>0;i--)
    {
    	if(value&0x80)
    	    MF522_SI_PIN_high();
    	else
    	    MF522_SI_PIN_low();
    	MF522_SCK_PIN_high();
        value <<= 1;
        MF522_SCK_PIN_low();
    }
    MF522_NSS_PIN_high();
    MF522_SCK_PIN_high();
}

/////////////////////////////////////////////////////////////////////
//功    能：置RC522寄存器位
//参数说明：reg[IN]:寄存器地址
//          mask[IN]:置位值
/////////////////////////////////////////////////////////////////////
void SetBitMask(unsigned char reg,unsigned char mask)
{
    char tmp = 0x0;
    tmp = ReadRawRC(reg);
    WriteRawRC(reg,tmp | mask);  // set bit mask
}

/////////////////////////////////////////////////////////////////////
//功    能：清RC522寄存器位
//参数说明：reg[IN]:寄存器地址
//          mask[IN]:清位值
/////////////////////////////////////////////////////////////////////
void ClearBitMask(unsigned char reg,unsigned char mask)
{
    char tmp = 0x0;
    tmp = ReadRawRC(reg);
    WriteRawRC(reg, tmp & ~mask);  // clear bit mask
}

/////////////////////////////////////////////////////////////////////
//功    能：通过RC522和ISO14443卡通讯
//参数说明：Command[IN]:RC522命令字
//          pInData[IN]:通过RC522发送到卡片的数据
//          InLenByte[IN]:发送数据的字节长度
//          pOutData[OUT]:接收到的卡片返回数据
//          *pOutLenBit[OUT]:返回数据的位长度
/////////////////////////////////////////////////////////////////////
char PcdComMF522(unsigned char Command,
                 unsigned char *pInData,
                 unsigned char InLenByte,
                 unsigned char *pOutData,
                 unsigned int  *pOutLenBit)
{
    char status = MI_ERR;
    unsigned char irqEn   = 0x00;
    unsigned char waitFor = 0x00;
    unsigned char lastBits;
    unsigned char n;
    unsigned int i;
    switch (Command)
    {
       case PCD_AUTHENT:
          irqEn   = 0x12;
          waitFor = 0x10;
          break;
       case PCD_TRANSCEIVE:
          irqEn   = 0x77;
          waitFor = 0x30;
          break;
       default:
         break;
    }

    WriteRawRC(ComIEnReg,irqEn|0x80);
    ClearBitMask(ComIrqReg,0x80);
    WriteRawRC(CommandReg,PCD_IDLE);
//    WriteRawRC(CommandReg,0x01);
//    printf("[%d] CommandReg\r\n",ReadRawRC(CommandReg));
//   WriteRawRC(CommandReg,0x02);
//    printf("[%d] CommandReg2\r\n",ReadRawRC(CommandReg));
    SetBitMask(FIFOLevelReg,0x80);

    for (i=0; i<InLenByte; i++)
    {   WriteRawRC(FIFODataReg, pInData[i]);
//    printf("[%d] pInData[i]\r\n",pInData[i]);
    }
    WriteRawRC(CommandReg, Command);
    if (Command == PCD_TRANSCEIVE)
    {    SetBitMask(BitFramingReg,0x80);  }

//    i = 600;//根据时钟频率调整，操作M1卡最大等待时间25ms
 i = 2000;
    do
    {
         n = ReadRawRC(ComIrqReg);
//         printf("[%d] ComIrqRegr\r\n",ReadRawRC(ComIrqReg));
         i--;
    }
    while ((i!=0) && !(n&0x01) && !(n&waitFor));
    ClearBitMask(BitFramingReg,0x80);

    if (i!=0)
    {
//    	   printf("[%d] ErrorReg\r\n",ReadRawRC(ErrorReg));
         if(!(ReadRawRC(ErrorReg)&0x1B))
         {
             status = MI_OK;
//             printf("[%d] status4!!\r\n",status);
             if (n & irqEn & 0x01)
             {   status = MI_NOTAGERR;   }
             if (Command == PCD_TRANSCEIVE)
             {
               	n = ReadRawRC(FIFOLevelReg);
//               	printf("[%d] n\r\n",n);
              	lastBits = ReadRawRC(ControlReg) & 0x07;
//              	printf("[%d] ControlReg\r\n",ReadRawRC(ControlReg));
//              	printf("[%d] lastBits\r\n",lastBits);
                if (lastBits)
                {   *pOutLenBit = (n-1)*8 + lastBits;   }
                else
                {   *pOutLenBit = n*8;   }
//                printf("[%d] unLen\r\n",*pOutLenBit);
                if (n == 0)
                {   n = 1;    }
                if (n > MAXRLEN)
                {   n = MAXRLEN;   }
                for (i=0; i<n; i++)
                {   pOutData[i] = ReadRawRC(FIFODataReg);
//                printf("[%d] FIFODataRegr\n",FIFODataReg);
                }
            }
         }
         else
         {   status = MI_ERR;   }

   }
//    printf("[%d] status5\r\n",status);

   SetBitMask(ControlReg,0x80);           // stop timer now
   WriteRawRC(CommandReg,PCD_IDLE);
   return status;
}


/////////////////////////////////////////////////////////////////////
//开启天线
//每次启动或关闭天险发射之间应至少有1ms的间隔
/////////////////////////////////////////////////////////////////////
void PcdAntennaOn()
{
    unsigned char i;
    i = ReadRawRC(TxControlReg);
    if (!(i & 0x03))
    {
        SetBitMask(TxControlReg, 0x03);
    }
}


/////////////////////////////////////////////////////////////////////
//关闭天线
/////////////////////////////////////////////////////////////////////
void PcdAntennaOff()
{
    ClearBitMask(TxControlReg, 0x03);
}

void InitializeSystem()
{
	PcdReset();
	PcdAntennaOff();
	delay_ms(2);
	PcdAntennaOn();
	M500PcdConfigISOType( 'A' );
}

void Datapro(unsigned char a[4],unsigned char b[8])
{
	//DeepLoud();
	if(a[0]%16>9)
		b[0] = a[0]%16+0x37;
	else
		b[0] = a[0]%16+0x30;

	if(a[0]/16>9)
		b[1] = a[0]/16+0x37;
	else
		b[1] = a[0]/16+0x30;

	if(a[1]%16>9)
		b[2] = a[1]%16+0x37;
	else
		b[2] = a[1]%16+0x30;

	if(a[1]/16>9)
		b[3] = a[1]/16+0x37;
	else
		b[3] = a[1]/16+0x30;

	if(a[2]%16>9)
		b[4] = a[2]%16+0x37;
	else
		b[4] = a[2]%16+0x30;

	if(a[2]/16>9)
		b[5] = a[2]/16+0x37;
	else
		b[5] = a[2]/16+0x30;

	if(a[3]%16>9)
		b[6] = a[3]%16+0x37;
	else
		b[6] = a[3]%16+0x30;

	if(a[3]/16>9)
		b[7] = a[3]/16+0x37;
	else
		b[7] = a[3]/16+0x30;
}

void RC522main(void)
{

    unsigned char Status = 1;
    InitializeSystem();
//    printf("[%s] init OK!\r\n");
//    printf("[%d] status1\r\n",Status);
//    	while(1)										//	 char PcdRequest(unsigned char req_code,unsigned char *pTagType)
    	{
    		Status = PcdRequest(PICC_REQALL,CT);	     //寻天线内全部卡
//    		 printf("[%d] status2\r\n",Status);
 		// pTagType[OUT]：卡片类型代码
//                0x4400 = Mifare_UltraLight
//                0x0400 = Mifare_One(S50)
//                0x0200 = Mifare_One(S70)
//                0x0800 = Mifare_Pro(X)
//                0x4403 = Mifare_DESFire
		Status = PcdAnticoll(SN);
//		printf("[%d] status!3!\r\n",Status);//char PcdAnticoll(unsigned char *pSnr)	  //功能：防冲撞
											        	//参数说明: pSnr[OUT]:卡片序列号，4字节



		if(Status==MI_OK)
		{
			Datapro(SN,DIS);
			printf("[%d] DIS\r\n",DIS);
			if(DIS[0]=='4'&&DIS[2]=='5')
			{
				printf("pass!\r\n");
				Beep_PIN_high();
				LED_GREEN_PIN_low();
				delay_ms(1000);
				LED_GREEN_PIN_high();
				delay_ms(1000);

			}

		 }
    }

}

